package com.android.delivery.receiver;

import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Desc:桌面应用程序角标更新工具
 * <p>
 * 华为： 实时更新，与首页tab总未读数一致，离线推送由服务端配置更新
 *      （全推消息，比如官方消息，主题精选，服务端下发的角标会为1，角标会更新为1；离线通知栏只累加1，不一定为真正未读数）
 * 小米： app在前台没有角标。后台或者离线状态下，每收到一条通知栏角标加1，每清除一条通知栏角标减1
 *      (如果通知栏消息被收到不重要通知，不会显示角标)
 * 三星： 实时更新，与首页tab总未读数一致。
 *       （推送只能触发显示角标不能更新角标数，广播只能更新角标数不能触发显示角标。三星由于没有离线推送所以离线状态下不能更新)
 * OPPO 一加： 角标权限开启情况下，有通知栏可以显示小红点
 * vivo 魅族： 不支持。
 *
 * <p>
 * Author: jiangwenxin
 * Date: 2019/11/29
 * Copyright: Copyright (c) 2010-2018
 * Company: @咪咕动漫
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class AppBadgeUtil {

    /**
     * Desc:通知栏设置角标
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param context
     * @param notification
     * @param badgeCount
     * @return boolean
     */
    public static boolean setNotificationBadgeCount(final Context context, Notification notification, final int badgeCount) {
        if (context != null) {
            Log.d("BRAND", Build.BRAND);
            switch (Build.BRAND.toLowerCase()) {
                case "xiaomi":
                    setXiaomiBadgeCount(badgeCount, notification);
                    return true;
//                case "huawei":
//                case "honor":
//                    return showHuaweiBadgeCount(context, badgeCount);
//                case "samsung":
//                    return setSamsungBadgeCount(context, badgeCount);
                default:
//                    return setNotificationBadge(count, context);
            }
        }
        return false;
    }


    /**
     * Desc:设置应用角标
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-10
     *
     * @param context
     * @param badgeCount 角标要显示的值
     * @return boolean
     */
    public static boolean setBadgeCount(final Context context, final int badgeCount) {
        if (context != null) {
            Log.d("BRAND", Build.BRAND);
            switch (Build.BRAND.toLowerCase()) {
                case "huawei":
                case "honor":
                    return showHuaweiBadgeCount(context, badgeCount);
                case "samsung":
                    return setSamsungBadgeCount(context, badgeCount);
            }
        }
        return false;
    }


    /**
     * Desc: 华为不需要依赖通知栏 直接更新角标
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param context
     * @param count   最终显示角标数量
     * @return boolean
     */
    public static boolean showHuaweiBadgeCount(Context context, int count) {
        try {
            String launchClassName = getLauncherClassName(context);
            if (TextUtils.isEmpty(launchClassName)) {
                return false;
            }
            Bundle bundle = new Bundle();
            //package = com.hisunflytone.android
            //class=com.migucc.module.home.mvp.ui.init.InitActivity
            bundle.putString("package", context.getPackageName());
            bundle.putString("class", launchClassName);
            bundle.putInt("badgenumber", count);
            context.getContentResolver().call(
                    Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bundle);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Desc:依赖通知栏设置角标更新
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param count        角标值以通知栏为单位叠加，若是覆盖通知栏，角标值覆盖，若是新增通知栏，角标值增加。                     目前小米每个通知栏角标加1
     * @param notification
     */
    private static void setXiaomiBadgeCount(int count, Notification notification) {
        try {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int
                    .class);
//            method.invoke(extraNotification, count);
            method.invoke(extraNotification, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Desc:更新角标
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param context
     * @param count
     * @return boolean
     */
    public static boolean setSamsungBadgeCount(Context context, int count) {
        try {
            String launcherClassName = getLauncherClassName(context);
            if (TextUtils.isEmpty(launcherClassName)) {
                return false;
            }
            Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
            intent.putExtra("badge_count", count);
            intent.putExtra("badge_count_package_name", context.getPackageName());
            intent.putExtra("badge_count_class_name", launcherClassName);
            context.sendBroadcast(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Desc:
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param context
     * @return string
     */
    private static String getLauncherClassName(Context context) {
        ComponentName launchComponent = getLauncherComponentName(context);
        if (launchComponent == null) {
            return "";
        } else {
            return launchComponent.getClassName();
        }
    }

    /**
     * Desc:
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-06
     *
     * @param context
     * @return component name
     */
    private static ComponentName getLauncherComponentName(Context context) {
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context
                .getPackageName());
        if (launchIntent != null) {
            return launchIntent.getComponent();
        } else {
            return null;
        }
    }

    /**
     * Desc: 是否是支持角标设置绝对值的机型（而不是累加值）
     * <p>
     * Author: jiangwenxin
     * Date: 2019-12-12
     *
     * @return boolean
     */
    public static boolean isSupportRealBadgeDevice() {
        if ("huawei".equals(Build.BRAND.toLowerCase()) ||
                "honor".equals(Build.BRAND.toLowerCase()) ||
                "samsung".equals(Build.BRAND.toLowerCase())) {
            return true;
        }
        return false;
    }
}
